//
// Created by yuping.li on 10/17/24.
//

#ifndef DELAY_HPP_
#define DELAY_HPP_

#include <cstdint>
#include "main.h"

class Delay {
public:

  static Delay& instance() {
    static Delay instance;
    return instance;
  }
  
  void init(uint32_t sys_clk) {
    m_fac_us = sys_clk;
  }

  void delay_us(uint32_t nus) const {
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;        /* LOAD的值 */
    ticks = nus * m_fac_us;                 /* 需要的节拍数 */

    told = SysTick->VAL;                    /* 刚进入时的计数器值 */
    while (true) {
      tnow = SysTick->VAL;
      if (tnow != told) {
        if (tnow < told) {
          tcnt += told - tnow;        /* 这里注意一下SYSTICK是一个递减的计数器就可以了 */
        } else {
          tcnt += reload - tnow + told;
        }
        told = tnow;
        if (tcnt >= ticks) {
          break;                      /* 时间超过/等于要延迟的时间,则退出 */
        }
      }
    }
  }
  
protected:
  uint32_t m_fac_us{0};       /* us延时倍乘数 */
  Delay() = default;
};

#endif //DELAY_HPP_
